package com.jdcjk.project.setting;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.jdcjk.GlobalParams;
import com.jdcjk.UrlAddress;
import com.jdcjk.util.CommonMethod;
import com.jdcjk.util.GaoDeMapUtil;
import com.jdcjk.util.LocationUtil;
import com.jdcjk.util.PreferencesUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

/**
 * Created by Administrator on 2017/3/21 0021.
 */

public class PositionReportService extends Service {
    private final String TAG = PositionReportService.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        //开启GPS定位
        initGps();
        //上报频度
        String delayTimeString = PreferencesUtils.getString(PositionReportService.this, PreferencesUtils.REPORT_TIME_FREQUENCY);
        int delayTime = Integer.valueOf(delayTimeString.equals("") ? "5" : delayTimeString) * 1000;
        handler.postDelayed(runnable, delayTime); //每隔delayTime s执行
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void initGps() {
//        refreshGPSState();
        //开启高德地图定位
        initBaiduLocation();
    }

    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient;

    public void initBaiduLocation() {
        mlocationClient = new AMapLocationClient(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //定位成功回调信息，设置相关消息
                        aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                        LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                        latLng = GaoDeMapUtil.gcj_To_Gps84(latLng);//坐标转换
                        GlobalParams.gaodeLongitude = latLng.longitude;//获取经度
                        GlobalParams.gaodeLatitude = latLng.latitude;//获取纬度
                        GlobalParams.gaodeAltitude = aMapLocation.getAltitude();//获取高度
                        GlobalParams.gaodeSpeed = (float) (aMapLocation.getSpeed() * 3.6);//单位km/s
                        GlobalParams.gaodeDirection = aMapLocation.getBearing();//获取方向
                    } else {
                        //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
//                        Log.e("AmapError", "location Error, ErrCode:"
//                                + aMapLocation.getErrorCode() + ", errInfo:"
//                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        String delayTimeString = PreferencesUtils.getString(PositionReportService.this, PreferencesUtils.REPORT_TIME_FREQUENCY);
        int delayTime = Integer.valueOf(delayTimeString.equals("") ? "5" : delayTimeString) * 1000;
        mLocationOption.setInterval(delayTime);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }


    private LocationManager locationManager;
    private LocationUtil locationUtil;

    public void refreshGPSState() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationUtil = LocationUtil.getInstance(this, LocationUtil.GET_LOCATION_ALWAYS);
        locationUtil.setOnLocationReceiveListener(new LocationUtil.OnLocationReceiveListenerAdapter() {
            @Override
            public void onLocationReceive(LocationUtil.MyLocation mBaseLocation) {
                GlobalParams.gpsLongitude = mBaseLocation.getLongitude();
                GlobalParams.gpsLatitude = mBaseLocation.getLatitude();
                GlobalParams.gpsAltitude = mBaseLocation.getAltitude();
                GlobalParams.gpsSpeed = (float) CommonMethod.myRound((double) mBaseLocation.getSpeed(), 2);
                GlobalParams.gpsDirection = mBaseLocation.getDirection();
            }
        });
        locationUtil.startMonitor();
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            //上报手机号码
            String reportPhoneNumber = PreferencesUtils.getString(PositionReportService.this, PreferencesUtils.REPORT_PHONE_NUMBER);
            //上报频度
            String delayTimeString = PreferencesUtils.getString(PositionReportService.this, PreferencesUtils.REPORT_TIME_FREQUENCY);
            int delayTime = Integer.valueOf(delayTimeString.equals("") ? "5" : delayTimeString) * 1000;
            //车牌号码
            String licensePlateNumber = PreferencesUtils.getString(PositionReportService.this, PreferencesUtils.LICENSE_PLATE_NUMBER);
            //如果没有设置车牌号码则不上传位置
            if (licensePlateNumber.equals("")) {
                handler.postDelayed(this, delayTime);
                return;
            }
            OkHttpUtils.post()
                    .url(UrlAddress.SAVE_LOCATION)
                    .addParams("carId", licensePlateNumber)
                    .addParams("cardNum", reportPhoneNumber)
                    .addParams("longitude", String.valueOf(GlobalParams.gaodeLongitude))
                    .addParams("latitude", String.valueOf(GlobalParams.gaodeLatitude))
                    .addParams("speed", String.valueOf(GlobalParams.gaodeSpeed))
                    .addParams("direction", String.valueOf(GlobalParams.gaodeDirection))
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int i) {
                        }

                        @Override
                        public void onResponse(String s, int i) {
                        }
                    });
            handler.postDelayed(this, delayTime);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
        mlocationClient.stopLocation();//取消定位服务
        mlocationClient.onDestroy();//销毁定位服务
        mlocationClient = null;
    }

}
